
const baseUrl = import.meta.env.VITE_APP_BASE_API
const baseDifyUrl = import.meta.env.VITE_DIFY_APP_BASE_API

export async function createOllama3Stylized(text, chatId, conversationId, appId, fileUrl = '', fileSize = '', fileKey = '', uploadFileId, qaType, type, fplatformId = 1) {
    const userStore = useUserStore()
    const token = userStore.getUserToken()
    const businessStore = useBusinessStore()

    const url = `${baseUrl}/api/chat/comm/${fplatformId}/${appId}`

    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `${token}`
        },
        body: JSON.stringify({
            query: text,
            "userId": 1,
            "chatId": chatId,
            "conversationId": conversationId,
            "transferMethod": type ? "local_file" : '',
            "isFile": type ? true : false,
            uploadFileId,
            qaType,
            type,
            fileUrl,
            fileSize,
            fileKey
        })
    })
}

// parseStream 函数是辅助函数，无需修改
async function parseStream(stream) {
    const reader = stream.getReader();
    try {
        while (true) {
            const { done, value } = await reader.read();
            if (done) break;
            console.log('Received chunk:', value);
        }
        console.log('Stream complete');
    } catch (error) {
        console.error('Stream error:', error);
    } finally {
        reader.releaseLock();
    }
}


export async function login(username, password) {
    const url = `${baseUrl}/auth/login`

    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            username,
            password
        })
    })
}

export async function query_user_qa_record(page, limit, appId, isCommQa) {
    const userStore = useUserStore()
    const token = userStore.getUserToken()
    const url = `${baseUrl}/api/conv/query_user_record`

    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
            page,
            limit,
            appId,
            userId: '1',
            isCommQa
        })
    })
}

export async function delete_user_record(ids) {
    const userStore = useUserStore()
    const token = userStore.getUserToken()
    const url = `${baseUrl}/api/dify/delete_session`

    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
            chatId: ids
        })
    })
}

export async function update_user_record(ids, title) {
    const userStore = useUserStore()
    const token = userStore.getUserToken()
    const url = `${baseUrl}/api/dify/update_session`

    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
            chatId: ids,
            title: title
        })
    })
}

export async function search_user_record(title) {
    const userStore = useUserStore()
    const token = userStore.getUserToken()
    const url = `${baseUrl}/api/conv/search_user_record`

    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
            title: title,
            userId: '1'
        })
    })
}

export async function search_user_record_detail(chatId) {
    const userStore = useUserStore()
    const token = userStore.getUserToken()
    const url = `${baseUrl}/api/conv/query_user_record_detail`

    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
            chatId: chatId,
            userId: '1'
        })
    })
}

export async function fead_back(feadId, rating) {
    const userStore = useUserStore()
    const token = userStore.getUserToken()
    const url = `${baseUrl}/api/conv/dify_fead_back`

    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
            feadId,
            rating,
            userId: '1'
        })
    })
}

export async function getAppsList(name) {
    const userStore = useUserStore()
    const token = userStore.getUserToken()
    const url = `${baseUrl}/dify/apps/group2`

    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `${token}`
        },
        body: JSON.stringify({
            name,
            platformId: 1,
            userId: '1'
        })
    })
}

export async function getKnowledge(page = 1, limit = 10, keyword = '') {
    const userStore = useUserStore()
    const token = userStore.getUserToken()
    const url = `${baseUrl}/api/dset/comm/1`

    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `${token}`
        },
        body: JSON.stringify({
            "name": keyword,
            pageable: {
                page: page,
                size: limit,
            }
        })
    })
}

export async function getKnowledgeDocuments(dataset_id, keyword = '', page = 1, limit = 10) {
    const userStore = useUserStore()
    const token = userStore.getUserToken()
    const url = `${baseUrl}/api/dset/comm/1/${dataset_id}`

    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `${token}`
        },
        body: JSON.stringify({
            "name": keyword,
            pageable: {
                page: page,
                size: limit,
            }
        })
    })
}

export async function uploadFile(dataset_id, formData) {
    const userStore = useUserStore()
    const token = userStore.getUserToken()
    const url = `${baseUrl}/api/dset/comm/upload/file/1/${dataset_id}`

    return fetch(url, {
        method: 'POST',
        headers: {
            // 对于 FormData，不要手动设置 'Content-Type'，浏览器会自动处理并加上正确的 boundary
            'Authorization': `${token}`
        },
        body: formData
    })
}

export async function deleteFileList(dataset_id, document_id) {
    const userStore = useUserStore()
    const token = userStore.getUserToken()
    const url = `${baseUrl}/api/dset/comm/1/${dataset_id}/${document_id}`

    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `${token}`
        },
        // 如果后端接口允许空 body，这样写是正确的
        body: '' 
    })
}


// --- 注意：下面这些函数使用了 location.origin，它们会直接请求当前域名，不经过 /sanic 代理 ---
// 如果这些也需要代理，需要将 location.origin 改为 baseUrl

export async function dify_suggested(chat_id) {
    const userStore = useUserStore()
    const token = userStore.getUserToken()
    // 注意：这里使用的是 location.origin，它会直接请求前端服务器的根路径
    // 如果这个接口也需要被代理到后端，需要改成 baseUrl
    // 例如: const url = `${baseUrl}/dify/get_dify_suggested`
    const url = `${location.origin}/sanic/dify/get_dify_suggested`
    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
            chat_id
        })
    })
}

export async function word_to_md(file_key) {
    const userStore = useUserStore()
    const token = userStore.getUserToken()
    const url = `${location.origin}/sanic/ta/word_to_md`
    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
            file_key
        })
    })
}

export async function query_demand_records(page, limit) {
    const userStore = useUserStore()
    const token = userStore.getUserToken()
    const url = `${location.origin}/sanic/ta/query_demand_records`
    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
            page,
            limit
        })
    })
}

export async function insert_demand_manager(project_data) {
    const userStore = useUserStore()
    const token = userStore.getUserToken()
    const url = `${location.origin}/sanic/ta/insert_demand_manager`
    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
            project_data
        })
    })
}

export async function delete_demand_records(id) {
    const userStore = useUserStore()
    const token = userStore.getUserToken()
    const url = `${location.origin}/sanic/ta/delete_demand_records`
    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
            id
        })
    })
}

export async function abstract_doc_func(doc_id) {
    const userStore = useUserStore()
    const token = userStore.getUserToken()
    const url = `${location.origin}/sanic/ta/abstract_doc_func`
    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
            doc_id
        })
    })
}